package net.lahuobao.mall.controller.admin;

import net.lahuobao.enums.EOSSFolderName;
import net.lahuobao.mall.entity.admin.MallProductEntity;
import net.lahuobao.mall.entity.admin.MallProductRecommendEntity;
import net.lahuobao.mall.entity.admin.MallProductRecommendHistoryEntity;
import net.lahuobao.mall.service.admin.MallProductRecommendHistoryServiceI;
import net.lahuobao.mall.service.admin.MallProductRecommendServiceI;
import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**   
 * @Title: Controller
 * @Description: 商品推荐
 * @author zhangdaihao
 * @date 2016-09-12 13:50:15
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/mallProductRecommendController")
public class MallProductRecommendController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(MallProductRecommendController.class);

	@Autowired
	private MallProductRecommendServiceI mallProductRecommendService;

	@Autowired
	private MallProductRecommendHistoryServiceI mallProductRecommendHistoryServiceI;

	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;


	/**
	 * 商品推荐列表 页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/mall/admin/mallProductRecommendList");
	}

	/**
	 * easyui AJAX请求数据
	 *
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(MallProductRecommendEntity mallProductRecommend, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(MallProductRecommendEntity.class, dataGrid);

		//查询条件组装器e
		if (StringUtil.isNotEmpty(mallProductRecommend.getProductname())) {
			cq.like("productname", "%" + mallProductRecommend.getProductname() + "%");
			mallProductRecommend.setProductname(null);
		}

		if (StringUtil.isNotEmpty(mallProductRecommend.getRecommendtype())) {
			cq.eq("recommendtype", mallProductRecommend.getRecommendtype());
		}
		cq.addOrder("sort", SortDirection.asc);

		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallProductRecommend);

		this.mallProductRecommendService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除商品推荐
	 *
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(MallProductRecommendEntity mallProductRecommend, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		mallProductRecommend = systemService.getEntity(MallProductRecommendEntity.class, mallProductRecommend.getId());
		message = "商品推荐删除成功并存入历史推荐中";

		MallProductRecommendHistoryEntity historyEntity = new MallProductRecommendHistoryEntity();

		try {
			MyBeanUtils.copyBean2Bean(historyEntity, mallProductRecommend);
		} catch (Exception e) {
			e.printStackTrace();
		}
		mallProductRecommendHistoryServiceI.save(historyEntity);
		mallProductRecommendService.delete(mallProductRecommend);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

		j.setMsg(message);
		return j;
	}


	/**
	 * 添加商品推荐
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(params = "save", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson save(MallProductRecommendEntity mallProductRecommend, HttpServletRequest request) {
		// 转化request
		MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;

		CommonsMultipartFile file1 = (CommonsMultipartFile)rm.getFile("image");
		// 得到上传文件
		MultipartFile image = null;
		Map<String, MultipartFile> fileMap = rm.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			image = entity.getValue();// 获取上传文件对象
		}
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(mallProductRecommend.getId())) {
			message = "商品推荐更新成功";
			MallProductRecommendEntity t = mallProductRecommendService.get(MallProductRecommendEntity.class, mallProductRecommend.getId());
			try {
				if(null != image && image.getSize() > 0){
					mallProductRecommend.setImagesrc(uploadImage(image, mallProductRecommend.getRecommendtype() == 1 ? EOSSFolderName.RECOMMEND_PATH : EOSSFolderName.FINE_PATH));
				}
				MyBeanUtils.copyBeanNotNull2Bean(mallProductRecommend, t);
				mallProductRecommendService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "商品推荐更新失败";
			}
		} else {//添加
			message = "商品推荐添加成功";
			try {
				String url = uploadImage(file1, mallProductRecommend.getRecommendtype() == 1 ? EOSSFolderName.RECOMMEND_PATH : EOSSFolderName.FINE_PATH);
				mallProductRecommend.setImagesrc(url);
			} catch (Exception e) {
				message = "商品推荐添加失败";
				e.printStackTrace();
			}
			mallProductRecommend.setCreatetime(new Date());
			HttpSession session = ContextHolderUtils.getSession();
			TSUser user = (TSUser)session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
			mallProductRecommend.setCreateuserid(1);//user.getId();
			mallProductRecommendService.save(mallProductRecommend);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 商品推荐列表页面跳转
	 *
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(MallProductRecommendEntity mallProductRecommend, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(mallProductRecommend.getId())) {
			mallProductRecommend = mallProductRecommendService.getEntity(MallProductRecommendEntity.class, mallProductRecommend.getId());
			req.setAttribute("mallProductRecommendPage", mallProductRecommend);
		} else {//新增
			Integer productId = Integer.valueOf(req.getParameter("productId"));
			MallProductEntity mallProduct = systemService.getEntity(MallProductEntity.class, productId);
			MallProductRecommendEntity mallProductRecommendEntity = new MallProductRecommendEntity();
			mallProductRecommendEntity.setProductname(mallProduct.getProductname());
			mallProductRecommendEntity.setProductid(mallProduct.getId());
			req.setAttribute("mallProductRecommendPage", mallProductRecommendEntity);
		}
		return new ModelAndView("net/lahuobao/mall/admin/mallProductRecommend");
	}

	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<MallProductRecommendEntity> list() {
		List<MallProductRecommendEntity> listMallProductRecommends = mallProductRecommendService.getList(MallProductRecommendEntity.class);
		return listMallProductRecommends;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		MallProductRecommendEntity task = mallProductRecommendService.get(MallProductRecommendEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody MallProductRecommendEntity mallProductRecommend, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallProductRecommendEntity>> failures = validator.validate(mallProductRecommend);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallProductRecommendService.save(mallProductRecommend);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = mallProductRecommend.getId().toString();
		URI uri = uriBuilder.path("/rest/mallProductRecommendController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody MallProductRecommendEntity mallProductRecommend) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallProductRecommendEntity>> failures = validator.validate(mallProductRecommend);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallProductRecommendService.saveOrUpdate(mallProductRecommend);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		mallProductRecommendService.deleteEntityById(MallProductRecommendEntity.class, id);
	}


	@RequestMapping(value = "isHave", method = RequestMethod.POST)
	@ResponseBody
	public void isHave(MallProductRecommendEntity mallProductRecommend,HttpServletRequest request, HttpServletResponse response) {
		AjaxJson json = null;
		try {
			json = new AjaxJson();
			//判断推荐中是否已经存在
			CriteriaQuery cq = new CriteriaQuery(MallProductRecommendEntity.class);
			cq.eq("recommendtype", mallProductRecommend.getRecommendtype());
			cq.eq("productid", mallProductRecommend.getProductid());
			cq.add();
			List<MallProductRecommendEntity> list = mallProductRecommendService.getListByCriteriaQuery(cq, false);
			if(list.size() > 0){
                json.setSuccess(false);
				String msg = "该商品已经加入到";
				msg += mallProductRecommend.getRecommendtype().toString() == "1" ? "每日推荐" : "拉货宝精选,";
				msg += "请选择编辑!";
                json.setMsg(msg);
                return;
            }
			//判断推荐历史中是否存在
			MallProductRecommendHistoryEntity recommendHistory = new MallProductRecommendHistoryEntity();
			CriteriaQuery cqHistory = new CriteriaQuery(MallProductRecommendHistoryEntity.class);
			cqHistory.eq("recommendtype", mallProductRecommend.getRecommendtype());
			cqHistory.eq("productid", mallProductRecommend.getProductid());
			cqHistory.add();
			List<MallProductRecommendHistoryEntity>  recommendHistoryList = mallProductRecommendHistoryServiceI.
                    getListByCriteriaQuery(cqHistory, false);
			if(recommendHistoryList.size() > 0){
                json.setSuccess(false);
				String msg = "该商品已存在于推荐历史";
				msg += mallProductRecommend.getRecommendtype().toString() == "1" ? "每日推荐" : "拉货宝精选";
				msg += "中,请再推荐历史中选择恢复！";
				json.setMsg(msg);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			renderData(response, json);
		}
	}

}